package pers.ht.mbpo.service;


import pers.ht.mbpo.bean.Admin;
import pers.ht.mbpo.dao.AdminDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("UTF-8");

        String action = request.getParameter("action");
        if ("login".equals(action)) {
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            boolean flag = true;
            String msg = "";
            AdminDao userDao = new AdminDao();
            Admin loginAdmin = userDao.queryOne(username);
            if (username.equals(loginAdmin.getUsername()) && password.equals(loginAdmin.getPassword())) {
                request.getSession().setAttribute("loginAdmin", loginAdmin);
                response.sendRedirect("admin/index.jsp");
            } else if (loginAdmin.getUsername() == null) {
                flag = false;
                msg = "用户不存在！";
            } else {
                flag = false;
                msg = "用户名或密码错误，请重新输入！";
            }
            if (!flag) {
                request.setAttribute("msg", msg);
                request.setAttribute("username", username);
                request.getRequestDispatcher("admin/login.jsp").forward(request, response);
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/xml");
        response.setCharacterEncoding("UTF-8");
        String action = request.getParameter("action");
        if ("logout".equals(action)) {
            request.getSession().invalidate();
            response.sendRedirect("admin/login.jsp");
        }
    }
}
